<?php

namespace app\common\model;

use app\helpers\Common;

class Message extends Base
{
    protected $deleteTime = 'deleted_at';

    // 软删除字段默认值
    protected $defaultSoftDelete = 0;

    // 当前模型名称 不带前缀
    protected $name = 'msgs';

    public $pk = 'id';

    // 类型
    const TypeCode0 = 0;
    const TypeCode1 = 1;
    public static $typeList = [
        self::TypeCode0 => '系统消息',
        self::TypeCode1 => '文章消息',
    ];
    // 状态
    public static $statusList = [
        0 => '未读',
        1 => '已读',
    ];

    /**
     * 格式化列表数据
     */
    public static function formatDatas($list, $params = '')
    {
        foreach ($list as &$item) {
            $item = (new self())->formatItem($item, $params);
        }

        return $list;
    }

    /**
     * 格式化单个数据
     */
    public static function formatItem($item, $param = '')
    {
        if (!$item) {
            return '';
        }

        // 类型
        $item['type_name'] = self::$typeList[$item['type']];
        // 关联表
        $relatedInfo = [];
        switch ($item['type']) {
            case self::TypeCode0:
                $relatedInfo = [];
                break;
            case self::TypeCode1:
                $relatedInfo = Article::where('id', $item['related_id'])->find();
                break;
            default: break;
        }
        $item['related_info'] = $relatedInfo;
        if (isset($item['created_id']) && $item['created_id']) {
            $adminMdl = new \app\adminapi\model\Admin();
            $creator = $adminMdl->where('id', $item['created_id'])->field('nickname')->find();
            $item['created_name'] = $creator['nickname'] ?? '';
        } elseif ($item['created_id'] == 0) {
            $item['created_name'] = '系统';
        } else {
            $item['created_id'] = $relatedInfo['created_id'] ?? '';
            $item['created_name'] = $relatedInfo['created_name'] ?? '';
        }

        if (isset($param['source']) && $param['source'] == 'backend') {

        }

        return $item;
    }
}
